package cn.ibizlab.eam.core.extensions.service;

import cn.ibizlab.eam.core.eam_core.domain.EMItem;
import cn.ibizlab.eam.core.eam_core.domain.EMItemTrade;
import cn.ibizlab.eam.core.eam_core.domain.EMStock;
import cn.ibizlab.eam.core.eam_core.service.IEMStockService;
import cn.ibizlab.eam.core.eam_core.service.impl.EMItemPLServiceImpl;
import cn.ibizlab.eam.core.util.helper.Aops;
import cn.ibizlab.eam.util.dict.StaticDict;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.eam.core.eam_core.domain.EMItemPL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;

/**
 * 实体[损溢单] 自定义服务对象
 */
@Slf4j
@Primary
@Service("EMItemPLExService")
public class EMItemPLExService extends EMItemPLServiceImpl {

    @Autowired
    private IEMStockService emStockService;

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Confirm]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public EMItemPL confirm(EMItemPL et) {
        // 损溢单确认
        if(et.getEmitemplid().isEmpty()){
            throw new RuntimeException("损溢单不存在，无法完成操作");
        }
        // 首先判断交易记录存不存在
        EMItemTrade emItemTrade = emitemtradeService.get(et.getEmitemplid());
        if(emItemTrade == null){
            throw new RuntimeException("未找到已确认的收支单据，无法完成操作");
        }
        // 获得交易单价，总金额，交易量（带符号表示出与入）
        Double tradPrice = emItemTrade.getPrice();
        if(emItemTrade.getAmount() == null){
            emItemTrade.setAmount(emItemTrade.getPrice() * emItemTrade.getPsum());
        }
        Double tradeAmount = emItemTrade.getAmount();
        Double tradePsum = emItemTrade.getPsum();
        if(emItemTrade.getInoutflag() == 0){
            tradeAmount = emItemTrade.getAmount() * -1;
            tradePsum = emItemTrade.getPsum() * -1;
        }

        // 从物品表中找库存量，库存金额，平均价
        EMItem emItem = emitemService.get(emItemTrade.getItemid());
        // 库存量和库存金额为null时将其值设为0
        if(emItem.getStocksum() == null){
            emItem.setStocksum(0.0);
        }
        if(emItem.getAmount() == null){
            emItem.setAmount(0.0);
        }
        // 变更物品均价，总库存，总库存金额,物品表中的记录
        Double itemCnt = emItem.getStocksum() + tradePsum;
        Double changeAmount = 0.0;
        Double itemAmount = emItem.getAmount() + tradeAmount;
        Double itemPrice = 0.0;
        if(itemCnt == 0){
            changeAmount = emItem.getAmount();
            itemAmount = 0.0;
        }else if (itemCnt < 0){
            throw new RuntimeException("物品总库存不够，无法完成操作");
        }else {
            itemPrice = itemAmount/itemCnt;
        }
        // 库存表中查找物品对应的库存记录
        // 根据损溢物品的id,仓库id,库位id,批次，组织查找物品的库存数量
        EMStock query = new EMStock();
        query.setItemid(emItemTrade.getItemid());// 损溢物品id
        query.setStoreid(emItemTrade.getStoreid());// 物品存储的仓库id
        query.setStorepartid(emItemTrade.getStorepartid());// 物品存储的库位id;
        query.setBatcode(emItemTrade.getBatcode());// 批次
        query.setOrgid(emItemTrade.getOrgid()); // 组织
        EMStock emStock = emStockService.getOne(Wrappers.query(query));
        // 物品库存记录存在时
        if(emStock != null){
            // 对库存记录进行改变
            emStock.setStockcnt(emStock.getStockcnt() + tradePsum);
            if(emStock.getStockcnt() < 0){// 库存量不足时
                throw new RuntimeException("当前仓库物品库存不够，无法完成操作");
            }else if(emStock.getStockcnt() == 0){// 库存正好清0时，删除库存记录
                emStockService.remove(emStock.getEmstockid());
            }else {// 损溢后库存量还大于0时，更新库存记录
                emStockService.update(emStock);
            }
            // 出空原则，更新出库金额
            if(itemCnt == 0){
                emItemTrade.setAmount(changeAmount);
                emitemtradeService.update(Wrappers.query(emItemTrade).eq("INOUTFLAG", -1));
                et.setAmount(changeAmount);
            }
        }else{ // 物品库存不存在时
            EMStock stock = new EMStock();
            stock.setStockcnt(tradePsum);
            if(stock.getStockcnt() < 0){ // 库存量小于出库的数量时直接抛出错误，库存不足
                throw new RuntimeException("当前仓库物品库存不够，无法完成操作");
            }
            // 向库存表中插入一条新的库存记录
            stock.setItemid(emItemTrade.getItemid());
            stock.setStoreid(emItemTrade.getStoreid());
            stock.setStorepartid(emItemTrade.getStorepartid());
            stock.setBatcode(emItemTrade.getBatcode());
            stock.setOrgid(emItemTrade.getOrgid());
            emStockService.create(stock);
        }
        // 修改损溢单的状态
        et.setWfstep(null);
        et.setTradestate(Integer.valueOf(StaticDict.EMTRADESTATE.ITEM_20.getValue()));
        et.setEmitemplname(emItemTrade.getEmitemtradename());
        Aops.getSelf(this).update(et);

        // 更新物品表的库存，平均价，库存金额
        emItem.setAmount(itemAmount);
        emItem.setStocksum(itemCnt);
        emItem.setPrice(itemPrice);
        emItem.setStoreid(emItemTrade.getStoreid());
        emItem.setStorepartid(emItemTrade.getStorepartid());
        if(emItemTrade.getInoutflag() == 1){
            emItem.setLastindate(emItemTrade.getSdate());
            emItem.setLastaempid(emItemTrade.getAempid());
        }
//        emItem.setShfprice(); // 平均税费
        emitemService.update(emItem);

        return super.confirm(et);
    }

}

